package org.finesys.quartz.support;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.quartz.core.exception.TaskException;
import org.finesys.quartz.entity.SysJob;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * javaClass 调用实现
 */
@Component
@Slf4j
public class TaskInvokeJavaClassServiceImpl implements TaskInvokeService {

    @Override
    public void invoke(SysJob sysJob) throws TaskException {

        try {
            Class<?> classz = Class.forName(sysJob.getClassName());
            Object object = classz.newInstance();
            Method method;
            //支持参数
            if (StringUtils.hasText(sysJob.getMethodParamsValue())) {
                String[] params = sysJob.getMethodParamsValue().split(",");
                Class<?>[] parameterTypes = new Class[params.length];
                for (int i = 0; i < params.length; i++) {
                    parameterTypes[i] = String.class;
                }
                method = classz.getDeclaredMethod(sysJob.getMethodName(), parameterTypes);
                method.invoke(object, (Object[]) params);
            } else {
                method = classz.getDeclaredMethod(sysJob.getMethodName());
                method.invoke(object);
            }
        } catch (ClassNotFoundException e) {
            log.error("定时任务java反射类没有找到,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务java反射类没有找到,执行任务：" + sysJob.getClassName());
        } catch (InstantiationException e) {
            log.error("定时任务java反射类异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务java反射类异常,执行任务：" + sysJob.getClassName());
        } catch (IllegalAccessException e) {
            log.error("定时任务java反射类异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务java反射类异常,执行任务：" + sysJob.getClassName());
        } catch (NoSuchMethodException e) {
            log.error("定时任务java反射执行方法名异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务java反射执行方法名异常,执行任务：" + sysJob.getClassName());
        } catch (InvocationTargetException e) {
            log.error("定时任务java反射执行异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务java反射执行异常,执行任务：" + sysJob.getClassName());
        }
    }
}
